package cn.com.dhcc.turbo.web.controller.registry;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.Queue;
import cn.com.dhcc.turbo.entity.registry.tlq.TlqLq;
import cn.com.dhcc.turbo.entity.registry.tlq.TlqQcu;
import cn.com.dhcc.turbo.entity.registry.tlq.TlqSq;
import cn.com.dhcc.turbo.service.queue.tlq.TlqMoveService;
import cn.com.dhcc.turbo.service.queue.tlq.TlqOptService;
import cn.com.dhcc.turbo.service.queue.tlq.TlqQueueService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodePipelineService;
import cn.com.dhcc.turbo.service.registry.vo.PipeLineTlq;

import com.tongtech.tlq.admin.conf.LocalQue;
import com.tongtech.tlq.admin.conf.QCU;
import com.tongtech.tlq.admin.conf.SendQue;

@Controller
@RequestMapping("/registry")
@TurboMenu(belongToMenu=LEAF_MENU.TONGLINKQ_MGR)
public class TlqController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

	@Autowired
	@Qualifier(AppIocBean.TLQ_QUEUE_SERVICE_BEAN)
	private TlqQueueService queueService;
	
	@Autowired
	private TlqOptService tlqOptService;
	
	@Autowired
	private NodePipelineService nodePipelineService;
	
	@Autowired
	@Qualifier(AppIocBean.BASE_INFO_SERVICEIMPL_BEAN)
	private BaseInfoService baseInfoService;
	@Autowired
	private TlqMoveService tlqMoveService;

	/**
	 * QCU页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_qcu")
	public String list(Model model,String ip) {
		String msg = "";
		List<PipeLineTlq> tlqlines=null;
		try {
			tlqlines=nodePipelineService.listPipelineTlq();
			if (ip==null || "".equals(ip)) {
				ip=tlqlines.get(0).getBrokerIp();
			}
			Status tlqStatus = tlqOptService.getTlqStatus(ip);
			
			if (tlqStatus.isSuccess() && "Working".equals(tlqStatus.getData())) {
				tlqStatus = tlqOptService.getNodeSpvInfo();
				if (tlqStatus.isSuccess()) {
					Properties tlqInfo = (Properties) tlqStatus.getData();
					model.addAttribute("tlqInfo", tlqInfo);
				}
				
				tlqStatus = tlqOptService.getQCUState();
				if (tlqStatus.isSuccess()) {
					String qcuState = (String) tlqStatus.getData();
					model.addAttribute("qcuState", qcuState);
				}
				
				tlqStatus = tlqOptService.getQCUVO();
				if (tlqStatus.isSuccess()) {
					TlqQcu tlqQcu = (TlqQcu) tlqStatus.getData();
					model.addAttribute("tlqQcu", tlqQcu);
				}
				
				List<TlqLq> lqList = queueService.getRecvQueueList(ip);
				List<TlqSq> sqList = queueService.getSendQueueList(ip);
				
				model.addAttribute("lqList", lqList);
				model.addAttribute("sqList", sqList);
			}else{
				model.addAttribute("tlqStoped", true);
			}
		} catch (Exception e) {
			msg = "获取TLQ状态信息出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
		}
		model.addAttribute("tlqlines", tlqlines);
		model.addAttribute("ip", ip);
		return "registry/tlq_qcu";
	}
	
	
	
	/**
	 * QCU页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_qcu_edit")
	public String qcuEdit(Model model,String ip) {
		String msg = "";
		try {
			Status tlqStatus = tlqOptService.getTlqStatus(ip);
			if (tlqStatus.isSuccess() && "Working".equals(tlqStatus.getData())) {
				tlqStatus = tlqOptService.getQCUVO();
				if (tlqStatus.isSuccess()) {
					TlqQcu tlqQcu = (TlqQcu) tlqStatus.getData();
					model.addAttribute("tlqQcu", tlqQcu);
				}
			}
			model.addAttribute("ip", ip);
		} catch (Exception e) {
			msg = "获取TLQ状态信息出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
		}
		return "registry/tlq_qcu_edit";
	}
	
	
	/**
	 * 更新QCU
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_qcu_do_update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> qcuUpdate(
			Integer dyLocalQueMsgNum, 
			Integer dySendQueMsgNum,
			Integer dyLocalQueSpaceSize, 
			Integer dyLocalQueDataBuff, 
			Integer dySendQueSpaceSize,
			Integer dySendQueDataBuff,String ip) {
		String msg = "";
		try {
			Status status = tlqOptService.getQCU(ip);
			if (status.isSuccess()) {
				QCU qcu = (QCU)status.getData();
				qcu.setDyLocalQueMsgNum(dyLocalQueMsgNum);
				qcu.setDySendQueMsgNum(dySendQueMsgNum);
				qcu.setDyLocalQueSpaceSize(dyLocalQueSpaceSize);
				qcu.setDyLocalQueDataBuff(dyLocalQueDataBuff);
				qcu.setDySendQueSpaceSize(dySendQueSpaceSize);
				qcu.setDySendQueDataBuff(dySendQueDataBuff);
				
				status = tlqOptService.updatQCU(qcu);
				
				if (status.isSuccess()) {
					//sleeping 5 secs
					Thread.sleep(3000);
					msg = status.getMsg();
					return jsonSuccessResult(msg);
				}else{
					msg = status.getMsg();
					return jsonFailResult(msg);
				}
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "更新QCU过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	
	/**
	 * 停止QCU
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_stop_qcu", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> stopQcu(Model model,String ip) {
		String msg = "";
		try {
			Status status = tlqOptService.stopQCU(ip);
			if (status.isSuccess()) {
				msg = status.getMsg();

				Thread.sleep(20000);
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "停止QCU过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	
	/**
	 * 启动QCU
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_start_qcu", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> startQcu(Model model,String ip) {
		String msg = "";
		try {
			Status status = tlqOptService.startQCU(ip);
			if (status.isSuccess()) {
				msg = status.getMsg();

				Thread.sleep(20000);
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "停止QCU过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	/**
	 * 添加本地队列
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_lq_add")
	public String lqAdd(Model model) {
		String msg = "";
		try {
		} catch (Exception e) {
			msg = "添加本地队列出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
		}
		return "registry/tlq_lq_add";
	}
	
	/**
	 * 校验队列是否存在
	 * @param newNodeName
	 * @param orgCode
	 * @return
	 */
	@RequestMapping("/check_queue_name")
	@ResponseBody
	public String checkQueueName(String queueName) {
		try {
			if (!queueService.isExistQueue(queueName)) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (Exception e) {
			return FORM_CHECK_FAIL;
		}
	}
	
	
	/**
	 * 添加本地队列
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_add_lq", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addLq(Model model, Queue queue) {
		String msg = "";
		try {
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			queue.setId(UUIDGenerator.getUUID());
			queue.setNodeId(nodeInfo.getId());
			queue.setQueueType(Queue.QueueType.LQ.value());
			queue.setBrokerType(Queue.BrokerType.TLQ.value());
			queue.setMtime(new Date());

			Status status = queueService.addRecvQueue(queue);

			if (status.isSuccess()) {
				msg = status.getMsg();
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "添加本地队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	/**
	 * 初始化本地队列:仅仅是尝试在TLQ中添加对应的队列
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_lq_init", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> initLq(Model model, Queue queue) {
		String msg = "";
		try {
			logger.error("初始化本地队列:"+queue);
			Status status = tlqOptService.addRecvQueue(queue);
			if (status.isSuccess()) {
				msg = "初始化本地队列成功";
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "初始化本地队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 * 初始化发送队列:仅仅是尝试在TLQ中添加对应的队列
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_sq_init", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> initSq(Model model, Queue queue) {
		String msg = "";
		try {
			logger.error("初始化发送队列:"+queue);
			Status status = tlqOptService.addSendQueue(queue);
			if (status.isSuccess()) {
				msg = "初始化发送队列成功";
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "初始化发送队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	/**
	 * 删除本地队列和对应的数据库记录
	 * @param model
	 * @param id
	 * @param queueName
	 * @return
	 */
	@RequestMapping(value = "/tlq_lq_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteLq(Model model, String queueName) {
		String msg = "";
		try {
			Status status = tlqOptService.deleteRecvQueue(queueName);
			if (status.isSuccess()) {
				queueService.deleteByQueueName(queueName);
				msg = status.getMsg();
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "删除本地队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	/**
	 * 添加发送队列
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/tlq_sq_add")
	public String sqAdd(Model model) {
		String msg = "";
		try {
		} catch (Exception e) {
			msg = "添加本地队列出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
		}
		return "registry/tlq_sq_add";
	}
	
	
	/**
	 * 该方法尚未实现完成
	 * 删除发送队列和对应的数据库记录
	 * @param model
	 * @param id
	 * @param queueName
	 * @return
	 */
	@RequestMapping(value = "/tlq_sq_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteSq(Model model, String queueName) {
		String msg = "";
		try {
			Status status = tlqOptService.stopSq(queueName);
			if (status.isSuccess()) {
				Thread.sleep(5000);
				status = tlqOptService.deleteSendQueue(queueName);
				if (status.isSuccess()) {
					queueService.deleteByQueueName(queueName);
					msg = status.getMsg();
					return jsonSuccessResult(msg);
				} else {
					msg = status.getMsg();
					return jsonFailResult(msg);
				}
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "删除发送队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	
	
	/**
	 * 添加发送队列
	 * @param model
	 * @param queue
	 * @return
	 */
	@RequestMapping(value = "/tlq_add_sq", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addSq(Model model, Queue queue) {
		String msg = "";
		try {
			NodeInfo nodeInfo = baseInfoService.getCurrentNodeInfo();
			queue.setId(UUIDGenerator.getUUID());
			queue.setNodeId(nodeInfo.getId());
			queue.setQueueType(Queue.QueueType.SQ.value());
			queue.setBrokerType(Queue.BrokerType.TLQ.value());
			queue.setMtime(new Date());

			Status status = queueService.addSendQueue(queue);

			if (status.isSuccess()) {
				msg = status.getMsg();
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "添加本地队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 * 修改本地队列跳转
	 * @param model
	 * @param queueName
	 * @return
	 */
	@RequestMapping(value = "/tlq_lq_update")
	public String lqUpdate(Model model, String queueName) {
		String msg = "";
		try {
			LocalQue localQue = tlqOptService.getLqRecvQueue(queueName);
			model.addAttribute("localQue", localQue);
		} catch (Exception e) {
			msg = "获取本地队列失败" ;
			logger.error(msg, e);
		}
		return "registry/tlq_lq_update";
	}
	/**
	 * 修改本地队列
	 * @param model
	 * @param queue
	 * @return
	 */
	@RequestMapping(value = "/update_tlq_lq")
	@ResponseBody
	public Map<String, Object> updateLq(Model model, String queName,int msgNum,int msgSize,int queSpaceSize) {
		String msg = "";
		try {
			LocalQue localQue = tlqOptService.getLqRecvQueue(queName);
			localQue.setMsgNum(msgNum);
			localQue.setMsgSize(msgSize);
			localQue.setQueSpaceSize(queSpaceSize);
			Status status = tlqOptService.updateRecvQueue(localQue);
			if (status.isSuccess()) {
				msg = "修改本地队列成功";
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "修改本地队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 * 修改发送队列跳转
	 * @param model
	 * @param queueName
	 * @return
	 */
	@RequestMapping(value = "/tlq_sq_update")
	public String sqUpdate(Model model, String queueName) {
		String msg = "";
		try {
			SendQue sq = tlqOptService.getSendQue(queueName);
			model.addAttribute("sq", sq);
		} catch (Exception e) {
			msg = "获取本地队列失败" ;
			logger.error(msg, e);
		}
		return "registry/tlq_sq_update";
	}
	
	/**
	 * 修改发送队列
	 * @param model
	 * @param queue
	 * @return
	 */
	@RequestMapping(value = "/update_tlq_sq")
	@ResponseBody
	public Map<String, Object> updateSq(Model model, String queName,int msgNum,int msgSize,int queSpaceSize) {
		String msg = "";
		try {
			SendQue sq = tlqOptService.getSendQue(queName);
			sq.setMsgNum(msgNum);
			sq.setMsgSize(msgSize);
			sq.setQueSpaceSize(queSpaceSize);
			Status status = tlqOptService.updateSendQue(sq);
			if (status.isSuccess()) {
				msg = "修改发送队列成功";
				return jsonSuccessResult(msg);
			} else {
				msg = status.getMsg();
				return jsonFailResult(msg);
			}
		} catch (Exception e) {
			msg = "修改发送队列过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
	
	@RequestMapping(value = "/move_tlq")
	@ResponseBody
	public Map<String, Object> updateTlq(String fromIp,String toIp){
		String msg="";
		try {
			tlqMoveService.updateLocal(fromIp, toIp);
			return jsonSuccessResult("tlq从["+fromIp+"]"+"迁移到["+toIp+"]"+"成功!请重启项目，完成初始化...");
		} catch (ServiceException e) {
			msg = "tlq迁移过程出现异常:" + e.fillInStackTrace();
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}
}
